/**
 * 
 */
package string.passed;

import java.util.HashMap;

/**
 * @author xyyi
 *
 */
public class MinimumWindowSubstring {

	/**
	Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

	For example,
	S = "ADOBECODEBANC"
	T = "ABC"

	Minimum window is "BANC".

	Note:
	If there is no such window in S that covers all characters in T, return the emtpy string "".

	If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
	 */
	public String minWindow(String S, String T) {
		if (S == null || T == null || S.isEmpty() || T.isEmpty()
				|| S.length() < T.length())
			return "";
		// counter the number of c
		HashMap<Character, Integer> counter = new HashMap<Character, Integer>();
		for (char c : T.toCharArray()) {
			if (counter.containsKey(c))
				counter.put(c, counter.get(c) + 1);
			else
				counter.put(c, 1);
		}

		String result = "";
		int sizeToFind = T.length();
		int minWinSize = Integer.MAX_VALUE;
		int start = 0;

		for (int i = 0; i < S.length(); i++) {
			char currChar = S.charAt(i);
			if (counter.containsKey(currChar)) {
				if (counter.get(currChar) > 0)
					sizeToFind--;
				counter.put(currChar, counter.get(currChar) - 1);
			} else {
				counter.put(currChar, -1);
			}

			while (sizeToFind == 0) {
				int size = i - start + 1;
				if (size < minWinSize) {
					minWinSize = size;
					result = S.substring(start, i + 1);
				}
				char startChar = S.charAt(start);
				counter.put(startChar, counter.get(startChar) + 1);
				if (counter.get(startChar) > 0)
					sizeToFind++;
				start++;
			}
		}
		return result;
	}

	public String minWindow1(String S, String T) {
		if (S.length() < T.length())
			return "";
		HashMap<Character, Integer> counter = new HashMap<Character, Integer>();
		for (char c : T.toCharArray()) {
			if (counter.containsKey(c)) {
				counter.put(c, counter.get(c) + 1);
			} else {
				counter.put(c, 0);
			}
		}

		int index = 0;
		int minSize = Integer.MIN_VALUE;
		String result = null;
		int size = T.length();
		for (int i = 0; i < S.length(); i++) {
			char c = S.charAt(i);
			if (counter.containsKey(c)) {
				if (counter.get(c) > 1)
					size--;
			} else {
				counter.put(c, 1);
			}

			counter.put(c, counter.get(c) - 1);

			while (size == 0) {
				if (i - index + 1 > minSize) {
					minSize = i - index + 1;
					result = S.substring(index, i + 1);
				}
				char sChar = S.charAt(index);
				counter.put(sChar, counter.get(sChar) + 1);
				if (counter.get(sChar) > 0)
					size++;
				index++;
			}
		}

		return result;
	}

	/**
	 * 
	 */
	public MinimumWindowSubstring() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
